<template>
  <div class="top-right-btn">
    <el-row>
      <!-- 控制展示列头 -->
      <el-popover placement="bottom" popper-class="checkPop" trigger="click" v-model="columnsVisible">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
          class="allCheckbox"
        >全选
        </el-checkbox
        >
        <el-checkbox-group
          v-model="checkList"
          ref="columnsCheck"
          class="columnsCheck"
        >
          <template v-for="item in allColumns">
            <el-checkbox
              :label="item.property"
              v-if="filterCol.indexOf(item.property) === -1"
              :key="item.property"
            >{{ item.checkBoxLabel?item.checkBoxLabel:item.label }}
              <i class="el-icon-rank" v-if="enableSort" :key="item.property"></i>
            </el-checkbox>
          </template>

        </el-checkbox-group>

        <div class="checkPop_footer">
          <el-button type="success" size="small" @click="resetSort()"
          >确认
          </el-button
          >
        </div>

        <el-tooltip
          effect="dark"
          content="列设置"
          placement="top"
          v-if="tableRef"
          style="margin-right: 10px"
          slot="reference"
        >
          <el-button size="mini" circle icon="el-icon-menu"/>
        </el-tooltip>
      </el-popover>

      <!-- <el-tooltip class="item" effect="dark" content="导出" placement="top" v-if="tableRef">
        <el-button size="mini" circle icon="el-icon-download" @click="exportExcel()" />
      </el-tooltip> -->

      <el-tooltip
        class="item"
        effect="dark"
        :content="showSearch ? '隐藏搜索' : '显示搜索'"
        placement="top"
      >
        <el-button
          size="mini"
          circle
          icon="el-icon-search"
          @click="toggleSearch()"
        />
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        :content="setFull ? '放大' : '还原'"
        placement="top"
      >
        <el-button
          size="mini"
          circle
          :icon="setFull ? 'el-icon-zoom-in' : 'el-icon-zoom-out'"
          @click="toggleFull()"
        />
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="刷新" placement="top">
        <el-button
          size="mini"
          circle
          icon="el-icon-refresh"
          @click="refresh()"
        />
      </el-tooltip>
    </el-row>
  </div>
</template>
<script>
    import Sortable from "sortablejs";

    export default {
        name: "RightToolbar",
        data() {
            return {
                setFull: true,
                checkAll: false,
                isIndeterminate: true,
                checkList: [],
                table: null,
                visible: false,
                columnsVisible: false,
                checked: false,
                isManager: false,
                filterCol: ["selection", "index", "operation"],
                sortable: null
            };
        },
        props: {
            showSearch: {
                type: Boolean,
                default: true,
            },
            curPerms: {
                type: String,
                default: "system:user:list",
            },
            tableRef: {
                type: String
            },
            /*
               enableSort
               是否开启排序功能入库（默认为false）
               开启此选项请确保el-table-column为数据驱动模式（通过v-for渲染形式）
             */
            enableSort: {
                type: Boolean,
                default: false
            },
            defaultShowColumn: {
                type: Array,
                defaule: function () {
                    return []
                }
            },
            defaultHideColumn: {
                type: Array,
                defaule: function () {
                    return []
                }
            }
        },
        computed: {
            allColumns() {
                if (this.table) {
                    if (this.enableSort && this.table.$parent) {
                        return this.table.$parent.columnsList.map(item => {
                            return {
                                label: item.label,
                                property: item.prop
                            }
                        })
                    } else {
                        return this.table.columns
                    }
                }
            }
        },
        beforeDestroy() {
            if (this.sortable) {
                this.sortable.destroy()
            }
        },
        mounted() {
            // 是否开启列表设置功能
            if (this.tableRef) {
                this.$nextTick(() => {
                    this.initColumns()
                })
            }
            // 是否开启排序功能
            if (this.tableRef && this.enableSort) {
                let eles = Object.assign(this.findEl())
                let wrapperTr = this.$refs['columnsCheck'].$el
                this.sortable = Sortable.create(wrapperTr, {
                    handle: ".is-checked",
                    animation: 180,
                    delay: 0,
                    dragClass: "sortable-dragging",
                    onEnd: evt => {
                        if (evt.to.classList.contains('is-checked')) {
                            return false;
                        }
                        let oldItem = eles.$parent.columnsList[evt.oldIndex]
                        eles.$parent.columnsList.splice(evt.oldIndex, 1)
                        eles.$parent.columnsList.splice(evt.newIndex, 0, oldItem)
                        this.$nextTick(() => {
                            let sortArr = eles.$parent.columnsList.map(item => item.prop)
                            this.checkList.sort((a, b) => sortArr.indexOf(a) - sortArr.indexOf(b))
                        })
                    },
                    onMove: evt => {
                        if (!evt.related.classList.contains('is-checked')) {
                            return false
                        }
                    }
                })
            }

        },
        methods: {
            // 搜索
            toggleSearch() {
                this.$emit("update:showSearch", !this.showSearch);
            },
            // 刷新
            refresh() {
                this.$emit("queryTable");
            },
            // 放大
            toggleFull() {
                const app = document.querySelector(".app-main");
                if (app.getAttribute("class") === "app-main full") {
                    app.className = "app-main";
                    this.setFull = true;
                } else {
                    app.className += " full";
                    this.setFull = false;
                }
            },
            //  初始化列设置
            /*  查询逻辑：用户模板>全局模板>默认全选中
                1.优先查询用户设置的模板
                2.查询全局模板
                3.展示全部模板
            */
            initColumns() {
                this.checkList = [];
                this.table = Object.assign(this.findEl());
                this.table.columns.forEach((item, index) => {
                    // 预留一个备用宽度
                    this.$set(item, "copyWidth", item.width)
                    // 操作给key值
                    if (item.label === "操作") {
                        this.$set(item, "property", "operation");
                    }
                    if (item.type) {
                        if (item.type === "selection") {
                            this.$set(item, "property", "selection");
                            // this.$set(item, "label", "多选");
                        } else if (item.type === "index") {
                            this.$set(item, "property", "index");
                        } else if (item.type !== "default") {
                            this.$set(item, "checkBoxLabel", item.type + "-" + item.label);
                        }
                    }

                    if (!item.dataset?.defaultHide) {
                        this.checkList.push(item.property);
                    }
                    this.table.doLayout()
                });

                //判断是否包含默认展示列
                if ((this.defaultShowColumn?.length ?? 0) > 0) {
                    this.checkList = this.defaultShowColumn
                }

                //判断是否包含默认排除列
                if ((this.defaultHideColumn?.length ?? 0) > 0) {
                    this.checkList = this.checkList.filter(e => this.defaultHideColumn.indexOf(e) === -1)
                }

                this.resetSort()

                // // 是否有设置全局模板的权限
                // getManager().then((res) => {
                //     if (res.data) {
                //         this.isManager = true;
                //         this.checked = true;
                //     }
                // });
                // 当前用户模板/全局模板
                // userColumns(this.$route.meta.menuId).then((res) => {
                //     if (res.data) {
                //         this.checkList = res.data
                //         this.resetSort()
                //     }
                // });
            },
            // 寻找table元素
            findEl(ele = this.$parent) {
                if (ele.$refs[this.tableRef]) {
                    return Object.assign(ele.$refs[this.tableRef]);
                } else {
                    return this.findEl(ele.$parent);
                }
            },
            resetSort() {
                let eles = Object.assign(this.findEl())
                if (this.enableSort && eles.$parent.columnsList) {
                    eles.$parent.columnsList.sort((a, b) => this.checkList.indexOf(a.prop) - this.checkList.indexOf(b.prop))
                    this.$nextTick(() => {
                        this.hideColoumns()
                    })
                } else {
                    this.hideColoumns()
                }
                this.columnsVisible = false
            },
            // 隐藏表格列
            hideColoumns() {
                let eles = Object.assign(this.findEl());
                eles.columns.forEach(ele => {
                    if (this.enableSort) {
                        eles.$parent.columnsList.forEach(column => {
                            if (column.prop == ele.property) {
                                this.$set(ele, 'width', column.width)
                                this.$set(ele, 'copyWidth', column.width)
                            }
                        })
                    }

                    if (this.checkList.indexOf(ele.property) < 0) {
                        this.$set(ele, "width", -1);
                        this.$set(ele, "className", "columns_visible");
                    } else {
                        this.$set(ele, "width", ele.copyWidth);
                        this.$set(ele, "className", "");
                    }
                })
                eles.doLayout()
            },
            // 全选
            handleCheckAllChange(val) {
                if (val) {
                    this.checkList = [];
                    this.table.columns.forEach((item) => {
                        this.checkList.push(item.property);
                    });
                } else {
                    this.checkList = this.checkList.filter(
                        (item) => this.filterCol.indexOf(item) !== -1
                    );
                }
                this.isIndeterminate = false;
            },
            //  设置模板
            /*  保存逻辑：用户模板>全局模板>默认全选中
                1.保存模板信息至用户模板
                2.如果该账号是管理员，接口会返回字段，弹窗是否设置为全局
                3.如点击确认，则调保存全局模板接口
            */
            settings() {
                let params = {
                    header: this.checkList,
                    menuId: this.$route.meta.menuId,
                    saveTemplate: this.checked && this.isManager ? 1 : 0,
                };
                // userColSave(params).then((res) => {
                //     if (res.code == 200) {
                //         this.msgSuccess("模板保存成功");
                //         // location.reload();
                //     }
                //     this.visible = false;
                // });
                // this.hideColoumns();
                this.resetSort()
            },
            // 导出
            // exportExcel() {
            //   let eles = Object.assign(this.findEl())
            //   let xlsxParam = { raw: true };//转换成excel时，使用原始的格式
            //   let wb = XLSX.utils.table_to_book(eles.$el,xlsxParam);//outTable为列表id
            //   let wbout = XLSX.write(wb, {
            //     bookType: "xlsx",
            //     bookSST: true,
            //     type: "array"
            //   });
            //   try {
            //     FileSaver.saveAs(
            //       new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),
            //       `${this.$route.meta.title}.xlsx`
            //     );
            //   } catch (e) {
            //     if (typeof console !== "undefined") console.log(e, wbout);
            //   }
            //   return wbout
            // }
        },
    };
</script>
<style>
  .checkPop.el-popover.el-popper[x-placement^="bottom"] {
    padding: 0;
  }
</style>

<style lang="scss" scoped>
  .allCheckbox {
    padding: 5px 10px;
  }

  .columnsCheck.el-checkbox-group {
    border-top: 1px solid #dcdfe6;
    border-bottom: 1px solid #dcdfe6;
    padding: 5px 10px;
    max-height: 300px;
    overflow-y: auto;

    ::v-deep label.el-checkbox {
      display: block !important;
      padding: 5px 0;
      font-size: 13px;
      margin: 0;

      .el-checkbox__inner {
        line-height: 20px;
      }

      .el-checkbox__label {
        width: calc(100% - 14px) !important;

        i {
          line-height: 20px;
          float: right;
        }

        i::after {
          content: '';
          display: block;
          clear: both;
        }
      }
    }
  }

  .checkPop_footer {
    display: flex;
    padding: 10px;
    justify-content: space-around;
  }

  .el-table__cell {
    z-index: 999;
  }

  ::v-deep .sortable-dragging {
    span {
      color: #515a6e !important;
      font-weight: bold;
    }
  }
</style>
